package com.weijianhuawen.wjblog.admin.event.subscriber;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weijianhuawen.wjblog.admin.event.PublishArticleEvent;
import com.weijianhuawen.wjblog.common.constants.Constants;
import com.weijianhuawen.wjblog.common.domain.dos.ArticleContentDo;
import com.weijianhuawen.wjblog.common.domain.dos.ArticleDo;
import com.weijianhuawen.wjblog.common.domain.mapper.ArticleContentMapper;
import com.weijianhuawen.wjblog.common.domain.mapper.ArticleMapper;
import com.weijianhuawen.wjblog.search.helper.LuceneHelper;
import com.weijianhuawen.wjblog.search.index.ArticleIndex;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.print.Doc;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description: 发布文章事件订阅者 消费文章发布事件
 * @date: 2024-11-05 21:39
 */

@Component
@Slf4j
public class PublishArticleSubscriber implements ApplicationListener<PublishArticleEvent> {
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private ArticleContentMapper articleContentMapper;
    @Autowired
    private LuceneHelper luceneHelper;
    @Override
    public void onApplicationEvent(PublishArticleEvent event) {
        // 消费发布文章事件
        Long articleId = event.getArticleId();
        // 获取当前线程名称
        String threadName = Thread.currentThread().getName();

        log.info("【发布文章事件订阅者】 线程：{}开始处理订阅者行为！", threadName );
        log.info("【文章发布事件订阅者】 开始消费！处理文章id：{}", articleId);

        // 搜索发布新文章
        ArticleDo articleDo = articleMapper.selectByArticleId(articleId);
        ArticleContentDo articleContentDo = articleContentMapper.selectByArticleId(articleId);

        // 构建文档
        Document document = new Document();
        document.add(new TextField(ArticleIndex.COLUMN_TITLE, articleDo.getTitle(), Field.Store.YES));
        document.add(new TextField(ArticleIndex.COLUMN_ID, String.valueOf(articleDo.getId()), Field.Store.YES));
        document.add(new TextField(ArticleIndex.COLUMN_CREATE_TIME, Constants.DATE_TIME_FORMATTER.format(articleDo.getCreateTime()), Field.Store.YES));
        document.add(new TextField(ArticleIndex.COLUMN_COVER, articleDo.getCover(), Field.Store.YES));
        document.add(new TextField(ArticleIndex.COLUMN_SUMMARY, articleDo.getSummary(), Field.Store.YES));
        document.add(new TextField(ArticleIndex.COLUMN_CONTENT, articleContentDo.getContent(), Field.Store.YES));

        // 添加文档
        Long count = luceneHelper.addDocument(ArticleIndex.NAME, document);
        log.info("【文章发布事件订阅者】 完成！受影响文档数：{}", count);
    }
}
